import { useState, useCallback, useEffect } from 'react';
import { customerService } from '../services/customerService';
import type { Customer } from '../types';

interface UseCustomersReturn {
  customers: Customer[];
  error: string | null;
  refresh: () => Promise<void>;
  cacheStatus: {
    isInitialized: boolean;
    isLoading: boolean;
    lastFetchTime: number;
    cacheAge: number;
    customerCount: number;
  };
}

/**
 * 客户数据管理Hook
 * 统一管理高潜客户数据的获取、缓存和刷新
 * 基于customerService实现，提供响应式数据更新
 */
export const useCustomers = (): UseCustomersReturn => {
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [cacheStatus, setCacheStatus] = useState(customerService.getCacheStatus());

  // 加载客户数据
  const loadCustomers = useCallback(async () => {
    try {
      setError(null);
      const data = await customerService.getAllCustomers();
      setCustomers(data);
      // 只在数据加载完成后更新缓存状态
      setCacheStatus(customerService.getCacheStatus());
    } catch (err) {
      setError(err instanceof Error ? err.message : '加载客户数据失败');
      console.error('Failed to load customers:', err);
    }
  }, []);

  // 刷新客户数据
  const refresh = useCallback(async () => {
    try {
      setError(null);
      const data = await customerService.refreshCustomers();
      setCustomers(data);
      // 只在数据刷新完成后更新缓存状态
      setCacheStatus(customerService.getCacheStatus());
    } catch (err) {
      setError(err instanceof Error ? err.message : '刷新客户数据失败');
      console.error('Failed to refresh customers:', err);
    }
  }, []);

  // 初始化时加载数据
  useEffect(() => {
    loadCustomers();
  }, [loadCustomers]);

  return {
    customers,
    error,
    refresh,
    cacheStatus
  };
};
